<template>
  <div class="ms-list">
    <el-row class="operation">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">
          <icon style="color: #0088cc" name="home"></icon>
        </el-breadcrumb-item>
        <el-breadcrumb-item>数据中心</el-breadcrumb-item>
        <el-breadcrumb-item>区域报表</el-breadcrumb-item>
        <el-breadcrumb-item>城市日报</el-breadcrumb-item>
        <el-breadcrumb-item>列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>

    <!--<ms-search :data="search.list" @click="updateConditions" @clickH="calculatedHeight"/>-->
    <div ref="msSearch"><ms-search :data="search" @click="updateConditions"/></div>

    <el-table
      size="small" stripe border
      v-loading="table.loading"

      :data="list"
      show-summary
      :summary-method="getSummaries"
      :highlight-current-row="true"
      :fit="true">
      <el-table-column prop="province" label="省" min-width="100" fixed="left"></el-table-column>
      <el-table-column prop="city" label="市" min-width="160"></el-table-column>
      <el-table-column
        v-for="(item, index) in collections"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        min-width="80" align="right" header-align="center">
      </el-table-column>
      <!--</el-table-column>-->
      <el-table-column prop="total" label="合计" min-width="95" fixed="right" align="right" header-align="center"></el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      layout="total, sizes, prev, pager, next, jumper"
      :current-page.sync="pagination.page"
      :total="pagination.totalRow"
      :page-size="pagination.pageSize"
      :page-sizes="pagination.pageSizes"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>

<script>
  import MsSearch from '@/components/common/Search.vue'
  import MsConfirmButton from '@/components/common/ConfirmButton.vue'
  import Api from '@/api/report/region-consumption'
  import ResponseParse from '@/utils/response-parse'
  import { CONDITION_TYPE, DATE_PICKER_SHOW_TYPE } from '@/utils/constants'
  import moment from 'moment'

  const year = moment().format('YYYY')
  const lastMonth = moment().subtract(1, 'months').format('MM')

  export default {
    components: {
      MsSearch,
      MsConfirmButton
    },
    created () {
      this.search = [
        {
          name: 'date',
          title: '日期',
          type: CONDITION_TYPE.DATE,
          value: year + '-' + lastMonth,
          visible: true,
          config: {
            type: DATE_PICKER_SHOW_TYPE.MONTH,
            format: 'yyyy-MM',
            valueFormat: 'yyyy-MM'
          }
        },
        {
          name: 'dataType',
          title: '数据类型',
          placeholder: '--请选择数据类型--',
          type: CONDITION_TYPE.SELECT,
          value: '总点击次数',
          visible: true,
          config: {
            list: [
              {value: 1, label: '总展现次数'},
              {value: 2, label: '总消费金额'},
              {value: 3, label: '总点击次数'},
              {value: 4, label: '总点击率'},
              {value: 5, label: '平均点击价格总数'},
              {value: 6, label: '总转化数'},
              {value: 7, label: '总转化成本'}
            ]
          }
        }
      ]
      this.requestList()
    },
    data () {
      return {
        search: [],
        list: [],
        table: {
          loading: true
        },
        collections: [],
        pagination: {}
//        PHeigh: document.documentElement.clientHeight - 120,
//        tbHeight: 100
      }
    },
//    mounted: function () {
//      this.$nextTick(function () { this.$set(this, 'tbHeight', this.PHeigh - this.$refs.msSearch.clientHeight) })
//    },
    methods: {
//      calculatedHeight () {
//        this.$nextTick(function () {
//          this.$set(this, 'tbHeight', this.PHeigh - this.$refs.msSearch.clientHeight)
//        })
//      },
      requestList () {
        this.table.loading = true
        let search = Object.assign({}, this.pagination, this.search.condition)
        if (search.date === undefined) {
          search.date = year + '-' + lastMonth
        }
        Api.listCityDaily({search: search}, response => {
          let status = response.status || 0
          let data = response.data || {}
          if (status === 200 || status === 204) {
            this.table.loading = false
            let body = data.map.data || {}
            let lastDay = data.map.lastDay || 0
            // 动态列头数据
            if (undefined !== lastDay && lastDay > 0) {
              this.collections = []
              for (let i = 1; i <= 31; i++) {
                let keyYear = search.date.split('-')[0]
                let keyMonth = search.date.split('-')[1]
                let today = keyYear * 10000 + keyMonth * 100 + i + ''
                let person = {}
                person.prop = today
                person.label = i + '日'
                this.collections.push(person)
              }
            }
            let dataType = 0
            if (this.search.condition === undefined) {
              dataType = 3
            } else {
              dataType = this.search.condition.dataType
            }
            this.list = []
            // 装配“省”，“市”数据
            for (let key in body) {
              const dataList = {}
              let str = key.split('-')
              dataList.province = str[0] === '' ? '-' : str[0]
              dataList.city = str[1]
              // 根据选择的数据类型装配数据
              dataList.total = 0
              for (let i = 0; i < lastDay; i++) {
                let p = this.collections[i].prop
                if (undefined === dataType) {
                  dataList[p] = body[key][p] === undefined ? 0 : body[key][p]['click']
                } else if (dataType === 1) {
                  dataList[p] = body[key][p] === undefined ? 0 : body[key][p]['impression']
                } else if (dataType === 2) {
                  dataList[p] = body[key][p] === undefined ? 0 : body[key][p]['costCoin']
                } else if (dataType === 3) {
                  dataList[p] = body[key][p] === undefined ? 0 : body[key][p]['click']
                } else if (dataType === 4) {
                  dataList[p] = body[key][p] === undefined ? 0 : body[key][p]['clickRatio']
                  dataList[p] = dataList[p].toFixed(2) + '%'
                } else if (dataType === 5) {
                  dataList[p] = body[key][p] === undefined ? 0 : body[key][p]['clickPrice'].toFixed(2)
                } else if (dataType === 6) {
                  dataList[p] = body[key][p] === undefined ? 0 : body[key][p]['translation']
                } else if (dataType === 7) {
                  dataList[p] = body[key][p] === undefined ? 0 : body[key][p]['translationCost']
                }
                dataList.total += parseFloat(dataList[p])
              }
              if (dataType === 4) {
                dataList.total = dataList.total.toFixed(2) + '%'
              } else if (dataType !== 1 && dataType !== 3) {
                dataList.total = dataList.total.toFixed(2)
              }
              this.list.push(dataList)
            }
            this.pagination = ResponseParse.singlepage(response.data.map.page)
//            if (this.pagination.totalRow === 0) {
//              this.tbHeight = ''
//            } else {
//              if (this.pagination.totalPage === this.pagination.page && Object.keys(this.list).length <= 15) {
//                this.tbHeight = ''
//              } else {
//                this.$set(this, 'tbHeight', this.PHeigh - this.$refs.msSearch.clientHeight)
//              }
//            }
          } else {
//            this.tbHeight = ''
            this.list = []
            this.$message.error(data.error || '获取数据失败')
          }
          this.table.loading = false
        })
      },
      handleSizeChange (val) {
        this.pagination.pageSize = val
        this.requestList()
      },
      handleCurrentChange (val) {
        this.pagination.page = val
        this.requestList()
      },
      updateConditions (conditions) {
        this.pagination.page = 1
        this.search.condition = conditions
        this.requestList()
      },
      getSummaries (param) {
        const {columns, data} = param
        const sums = []
        if (data.length === 0) {
          return sums
        }
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          if (index === 1) {
            sums[index] = '-'
          }
          const values = data.map(item => Number(item[column.property]))
          if (this.search[1].value === '总展现次数' || this.search[1].value === '总消费金额' ||
            this.search[1].value === '总点击次数' || this.search[1].value === '总转化数') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              if (this.search[1].value === '总展现次数' || this.search[1].value === '总点击次数') {
                sums[index] = sums[index].toFixed(0)
              } else {
                sums[index] = sums[index].toFixed(2)
              }
            } else {
              sums[index] = '-'
            }
          } else {
            sums[index] = '-'
          }
        })
        return sums
      }
    }
  }
</script>

<style lang="scss" scoped>

  /*覆盖样式*/
  /*.el-table-column-left {*/
  /*text-align: left !important;*/
  /*}*/
</style>

